import React from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useState, useEffect } from 'react'
// 引入接口
import { getDetailData, add } from '@/api/detail'
import { CartList } from '@/api/cart'
// 引入顶部导航组件
import NavBarCom from '@/components/NavBarCom'
// 引入数据类型声明文件
import { listItem } from '@/types/dataTypes'
// 引入antd组件
import { Space, Swiper, Tag } from 'antd-mobile'
// 引入样式
import '@/assert/detail.scss'
// 动作栏需要的组件
import { CartO } from '@react-vant/icons'
import { ActionBar } from 'react-vant'

type Props = {}

export default function Detail({ }: Props) {
  const navigate = useNavigate()
  const [detailObj, setDetailObj] = useState<listItem | {}>({})
  const par = useParams()
  const [num, setNum] = useState()//购物车小角标
  // console.log('par', par);
  useEffect(() => {
    // 数据渲染
    fn1()
  }, [])
  //  详情页数据  类型断言 
  const arr = [(detailObj as listItem).img1, (detailObj as listItem).img2, (detailObj as listItem).img3, (detailObj as listItem).img4,]
  const items = arr.map((item, index) => (
    <Swiper.Item key={index}>
      <div className='swiper'>
        <img src={item} alt="" />
      </div>
    </Swiper.Item>
  ))
  // 初始数据
  const fn1 = () => {
    // 不能将类型“undefined”分配给类型“string”,使用的时候直接断言它就是string
    getDetailData({ proid: par.proid as string }).then((res) => {
      console.log('详情页数据', res);
      if (res.data.code == 200) {
        setDetailObj(res.data.data)
      }
    })
  }
  // 点击加入购物车
  const addFn = () => {
    add({
      userid: localStorage.getItem('userid'),
      proid: par.proid,
      num: '1'
    }).then((res) => {
      console.log('加入购物车', res);
      if (res.data.code == '200') {
        // 更新购物车列表
        CartList({ userid: localStorage.getItem('userid') }).then((res) => {
          console.log('购物车列表', res);
          if (res.data.code == '200') {
            setNum(res.data.data.length)
          }
        })
      }
    })
  }

  return (
    <div>
      {/* 顶部导航组件 */}
      <NavBarCom>详情</NavBarCom>
      {/* 轮播图 */}
      <Swiper autoplay loop={true} autoplayInterval={1000} >{items}</Swiper>
      {/* 文本 */}
      <p className='price'>${(detailObj as listItem).originprice}</p>
      <div className='text'>
        <span className='tag'> <Tag color='danger'>自营</Tag></span>
        <span className='proname'>{(detailObj as listItem).proname}</span>
      </div>
      {/* 底部动作栏 */}
      <div className='demo-action-bar'>
        <ActionBar>
          <ActionBar.Icon icon={<CartO />} badge={{ content: num }} text='购物车' onClick={() => navigate('/cart')} />
          <ActionBar.Button type='warning' text='加入购物车' onClick={addFn} />
          <ActionBar.Button type='danger' text='立即购买' />
        </ActionBar>
      </div>
    </div>
  )
}